unit IEvent;

interface

uses
  Windows, IException;

type
  TWaitResult = (wrTimeOut, wrSignaled, wrFailed);

  TEvent = class
  protected
    m_Event: THandle;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Pulse;
    procedure SetEvent;
    function WaitFor(TimeOut: Cardinal): TWaitResult; overload;
    function WaitFor: TWaitResult; overload;
    property Handle: THandle read m_Event;
  end;

implementation

constructor TEvent.Create;
begin
  inherited Create;
  m_Event := CreateEvent(Nil, False, False, Nil);
  if m_Event = 0 then
    raise TException.Create(GetLastError(), 'CreateEvent');
end;

destructor TEvent.Destroy;
begin
  if m_Event<>0 then CloseHandle(m_Event);
  inherited Destroy;
end;

procedure TEvent.Pulse;
begin
  PulseEvent(m_Event);
end;

procedure TEvent.SetEvent;
begin
  Windows.SetEvent(m_Event);
end;

function TEvent.WaitFor(TimeOut: Cardinal): TWaitResult;
var ResCode: Cardinal;
begin
  ResCode := WaitForSingleObject(m_Event, TimeOut);
  if ResCode = WAIT_ABANDONED then
    Result := wrFailed
  else if ResCode = WAIT_OBJECT_0 then
    Result := wrSignaled
  else if ResCode = WAIT_TIMEOUT then
    Result := wrTimeOut
  else raise TException.Create(GetLastError(), 'WaitForSingleObject');
end;

function TEvent.WaitFor: TWaitResult;
var ResCode: Cardinal;
begin
  ResCode := WaitForSingleObject(m_Event, INFINITE);
  if ResCode = WAIT_ABANDONED then
    Result := wrFailed
  else if ResCode = WAIT_OBJECT_0 then
    Result := wrSignaled
  else if ResCode = WAIT_TIMEOUT then
    Result := wrTimeOut
  else raise TException.Create(GetLastError(), 'WaitForSingleObject');
end;

end.
